package com.wmz.springCloud.lb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyLb implements LoadBalancer{

    private AtomicInteger atomicInteger = new AtomicInteger(0);


    private final int incream(){
        int current;
        int next;

        do {
            current = this.atomicInteger.get();
            next = current >= 2147483647 ? 0 : current + 1;
        } while (!this.atomicInteger.compareAndSet(current,next)); {
            System.out.println("*******第几次访问，次数next: "+next);
            return next;
        }
    }

    private final int random(){
        int current;
        int next;
        Random random = new Random();

        random.setSeed(10000L);
        do {
            current = random.nextInt(1000);
            next = current >= 2147483647 ? 0 : current + 1;
        } while (!this.atomicInteger.compareAndSet(current,next)); {
            System.out.println("*******第几次访问，次数next: "+next);
            return next;
        }
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> list) {
        int index = incream() % list.size(); //得到服务器的下标位置
        return list.get(index);
    }
}
